import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useLocation } from "react-router-dom";
import { List, Grid, InfiniteScroll } from "antd-mobile";
import { createAction } from "@common/utils";
import { PUSH_PAGE_STACK } from "@store/global-state/action-types";
import { OrderCardTitle } from "@components";
import { loadOtherInOrderLines } from "@store/other-in/async-call";
import { SET_OTHER_IN_ORDER_LINES } from "@store/other-in/action-types";

const OtherInOrderLine = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const [hasMore, setHasMore] = useState(false);
  const currentOrder = useSelector(
    (state) => state.otherIn.currentOrder
  );
  const orderLines = useSelector((state) => state.otherIn.orderLines);
  const orderLineOffset = useSelector(
    (state) => state.otherIn.orderLineOffset
  );

  const Descriptions = ({ record }) => (
    <Grid columns={2} gap={8}>
      <Grid.Item>行号: {record.extlLineNum}</Grid.Item>
      <Grid.Item></Grid.Item>
      <Grid.Item>物料编码: {record.itemCode}</Grid.Item>
      <Grid.Item>物料名称: {record.itemName}</Grid.Item>
      <Grid.Item>规格型号: {record.spec}</Grid.Item>
      <Grid.Item>批次号: {record.batchNum}</Grid.Item>
      <Grid.Item>待入数量: {record.qty}</Grid.Item>
      <Grid.Item>入库仓库: {record.suName}</Grid.Item>
    </Grid>
  );

  const loadList = async ({ offset }) => {
    let orderId = searchParams.get("id");
    let payload = {
      orderId,
      offset: /^\d+$/.test(offset) ? offset : orderLineOffset,
      maxResult: 5,
      callback: (resp) => setHasMore(resp.payload.items.length >= 5),
    };
    await loadOtherInOrderLines(payload);
  };

  useEffect(() => {
    loadList({ offset: 0 });
    return () => {
      dispatch(createAction(SET_OTHER_IN_ORDER_LINES, { items: [], offset: 0 }));
    };
  }, []);

  const loadMore = async () => {
    await loadList({});
  };

  const handleClick = (record) => {
    let path = `/app/other-in/ops?id=${record.id}`;
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  return (
    <div style={{ marginTop: "45px" }}>
      <List>
        {orderLines.map((record, idx) => (
          <List.Item
            key={idx}
            style={{ backgroundColor: idx % 2 === 0 ? "#EBF2FD" : "#FFFAF1" }}
            description={<Descriptions record={record} />}
            onClick={() => handleClick(record)}
          >
            <OrderCardTitle title={`单号: ${currentOrder.orderNum}`} />
          </List.Item>
        ))}
      </List>
      <InfiniteScroll
        style={{ backgroundColor: "#F5F5F5" }}
        loadMore={loadMore}
        hasMore={hasMore}
        threshold="10"
      />
    </div>
  );
};

export default OtherInOrderLine;
